package tablet.module_user.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.lib.app.ARouterPathUtils;
import com.lib.app.CodeUtil;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.json_deal.lib_mgson.MGson;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.views.dialog.http.DialogUtils;
import com.lib.fastkit.views.recyclerview.zhanghongyang.base.ViewHolder;
import com.lib.http.call_back.HttpDialogCallBack;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.ui.activity.BaseAppActivity;
import com.lib.ui.adapter.BaseAdapter;
import com.lib.utls.glide.GlideConfig;
import com.lib.view.navigationbar.NomalNavigationBar;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import tablet.module_user.R;
import tablet.module_user.R2;
import tablet.module_user.bean.OperateBean;
import tablet.module_user.bean.StudentCollectedStudyResBean;
import tablet.module_user.bean.TeachResListBean;

/**
 * Created by Administrator on 2020/8/19 0019.
 */

@Route(path = ARouterPathUtils.Tablet_User_TeacherResActivity)
public class TeacherResActivity extends BaseAppActivity {

    @BindView(R2.id.webview)
    WebView webview;

    @BindView(R2.id.tv_title)
    TextView tvTitle;
    @BindView(R2.id.tv_grade)
    TextView tvGrade;
    @BindView(R2.id.tv_time)
    TextView tvTime;
    @BindView(R2.id.tv_collect)
    TextView tvCollect;
    @BindView(R2.id.tv_classdescribe)
    TextView tvClassdescribe;

    @BindView(R2.id.rv_list)
    RecyclerView rvList;

    @Autowired(name = "resId")
    int resId;
    @Autowired(name = "resJson")
    String resJson;

    DialogUtils dialogUtils;

    //装载课程列表中的文本
    private List<TextView> tvColotList = new ArrayList<>();
    private int startPosition;

    TeachResListAdapter resListAdapter;

    List<TeachResListBean.ObjBean> resListBeans = new ArrayList<>();

    //当前教辅资料的是否收藏   0-未收藏，1-已收藏
    private int isCollect = -1;

    @Override
    protected void onCreateView() {

        resId = getIntent().getIntExtra("resId", -1);
        resJson = getIntent().getStringExtra("resJson");

        initResView();

        //初始化右边教辅资料列表
        initTeachResData();

        //初始化首页点击录播课的详细信息
        initStudyResData();

        tvCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //发送关注状态到服务Res器
                sendCareStateToService();
            }
        });
    }

    private void initStudyResData() {

        if (StringUtil.isNotEmpty(resJson, true)) {

            StudentCollectedStudyResBean.ObjBean.RowsBean resDataBean = MGson.newGson().
                    fromJson(resJson, StudentCollectedStudyResBean.ObjBean.RowsBean.class);

            resId = resDataBean.getId();
            isCollect = 1;

            initTeachResItemData(resDataBean.getAssistant_url());

            //初始化教辅资料的文字描述以及关注状态
            initStudyResContent(resDataBean.getSmall_title(), resDataBean.getCreation_date(),
                    resDataBean.getGrade_name(), resDataBean.getSubject_name());
        }

    }

    private void initStudyResContent(String title, String createTime, String grade, String subject) {

        if (StringUtil.isNotEmpty(title, true)) {

            tvTitle.setText(title);
        }

        if (StringUtil.isNotEmpty(createTime, true)) {

            tvTime.setText(createTime);
        }

        if (StringUtil.isNotEmpty(grade, true) &&
                StringUtil.isNotEmpty(subject, true)) {

            tvGrade.setText(grade + " · " + subject);
        }

        //是否收藏，0-未收藏，1-已收藏
        if (isCollect > -1) {

            if (0 == isCollect) {
                tvCollect.setText("收藏");
            } else if (1 == isCollect) {
                tvCollect.setText("已收藏");
            }
        }


    }

    private void initResView() {

        initTitle();

        dialogUtils = new DialogUtils();

        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setSupportZoom(true);
//
//        webview.addJavascriptInterface(javaScriptFunction, "AndroidInterface");
        webview.setWebViewClient(client);

        webview.setFocusableInTouchMode(true);
        webview.setFocusable(true);

        resListAdapter = new TeachResListAdapter(this, resListBeans);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rvList.setLayoutManager(manager);
        rvList.setAdapter(resListAdapter);


    }

    protected void initTitle() {

        NomalNavigationBar navigationBar = new
                NomalNavigationBar.Builder(this)
                .setTitle("教辅资料")
                .builder();

    }

    //videoCollect的值来判断收藏还是取消   1---已收藏    0----收藏
    private void sendCareStateToService() {

        HttpUtils.with(this)
                .addParam("requestType", "ADD_OR_REMOVE_FAVORITES")
                .addParam("recorded_lesson_id", resId)
                .addParam("lok_or_jfzl", 1)
                .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                .execute(new HttpDialogCallBack<OperateBean>() {
                    @Override
                    public void onSuccess(OperateBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            if (0 == result.getObj().getIs_favorites()) {

                                showToast("取消收藏成功！");
                                tvCollect.setText("收藏");

                            } else if (1 == result.getObj().getIs_favorites()) {

                                showToast("恭喜您，收藏成功，可以在个人中心查看哦！");
                                tvCollect.setText("已收藏");
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }

    private void initTeachResData() {

        HttpUtils.with(this)
                .addParam("requestType", "TABLET_TEACHING_ASSISTANT_CLASS_DETAILS")
                .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                .addParam("id", resId)
                .execute(new HttpNormalCallBack<TeachResListBean>() {
                    @Override
                    public void onSuccess(TeachResListBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {
                            if (result.getObj() != null) {

                                if (resListBeans.size() > 0) {
                                    resListBeans.clear();
                                }
                                resListBeans.addAll(result.getObj());
                                resListAdapter.notifyDataSetChanged();
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }

    //webview显示教辅资料网页图片
    private void initTeachResItemData(String resUrl) {

        if (StringUtil.isNotEmpty(resUrl, true)) {
            webview.loadUrl(resUrl);
        }

    }

    private WebViewClient client = new WebViewClient() {


        @Override
        public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
            super.onPageStarted(webView, s, bitmap);

            dialogUtils.showNormalDialog(TeacherResActivity.this, "资料正在加载中...");
        }

        /**
         * 防止加载网页时调起系统浏览器
         */
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {

            LogUtil.e(url);

            //网页调用打电话时操作
            if (url.startsWith("tel:")) {

                startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            } else {
                webView.loadUrl(url);

            }

            return true;
        }


        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);

            dialogUtils.dismiss();
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_teacherres;
    }


    class TeachResListAdapter extends BaseAdapter<TeachResListBean.ObjBean> {

        public TeachResListAdapter(Context context, List<TeachResListBean.ObjBean> mData) {
            super(context, mData);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_recorddetail_list;
        }

        @Override
        protected void toBindViewHolder(ViewHolder holder, final int position, final List<TeachResListBean.ObjBean> mData) {

            final TeachResListBean.ObjBean objBean = mData.get(position);

            //获取并设置背景图片
            ImageView backImg = holder.getView(R.id.iv_backimg);

            Glide.with(TeacherResActivity.this)
                    .load(objBean.getCover_url())
                    .apply(GlideConfig.getRoundOptions(20))
                    .into(backImg);

            final TextView tvTitle = holder.getView(R.id.tv_title);
            tvColotList.add(tvTitle);
            tvTitle.setText(objBean.getSmall_title());

            if (startPosition == position) {
                tvTitle.setTextColor(getResources().getColor(R.color.c5));
            }

            //开始播放和播放中文本
//            final ImageView ivStartPlaying = holder.getView(R2.id.iv_playimg);
//            final TextView tvPlaying = holder.getView(R2.id.tv_playing);

            holder.getView(R.id.lin_item).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    initTitleColor();

                    //判断点击的位置与播放的位置是否相同
                    if (startPosition == position) {

                        showToast("当前资料正在展示中！");

                    } else {
                        startPosition = position;

                        resId = mData.get(position).getId();
                        isCollect = mData.get(position).getIs_favorites();

                        //初始化教辅资料信息及收藏状态
                        initStudyResContent(objBean.getSmall_title(), objBean.getCreation_date(),
                                objBean.getGrade_name(), objBean.getSubject_name());

                        //将点击位置的视频添加到播放中
                        initTeachResItemData(objBean.getAssistant_url());
                    }
                    tvTitle.setTextColor(getResources().getColor(R.color.c5));
                }
            });
        }

    }

    private void initTitleColor() {

        for (TextView textView : tvColotList) {
            textView.setTextColor(getResources().getColor(R.color.base_title));
        }

    }

}
